package com.hust360.percent.activity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Random;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.widget.TextView;

import com.hust360.percent.PercentApplication;
import com.hust360.percent.pojo.Area;
import com.hust360.percent.pojo.Area.AreaDAO;
import com.hust360.percent.pojo.AreaLocal;
import com.hust360.percent.pojo.Discount;
import com.hust360.percent.pojo.Discount.DiscountDAO;
import com.hust360.percent.pojo.DiscountLocal;
import com.hust360.percent.pojo.Image;
import com.hust360.percent.pojo.Shop;
import com.hust360.percent.pojo.UserLocal;
import com.hust360.percent.pojo.Shop.ShopDAO;
import com.hust360.percent.pojo.ShopLocal;
import com.hust360.percent.pojo.User;
import com.hust360.percent.utils.ActivityUtils;
import com.hust360.percent.utils.StorageUtils;

public class FirstRunActivity extends Activity {

	PercentApplication application;
	SharedPreferences sharedPreferences;
	ShopDAO shopDAO;
	DiscountDAO discountInfoDAO;
	SQLiteDatabase citydb;
	AreaDAO areaDAO;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ActivityUtils.addActivity(this);
		TextView textView = new TextView(this);
		textView.setText("the first time app lauch on this device");
		setContentView(textView);

		application = (PercentApplication) getApplication();
		sharedPreferences = application.getSharedPreferences();
		shopDAO = application.getShopDao();
		discountInfoDAO = application.getDiscountInfoDAO();
		areaDAO = application.getAreaDAO();
		/*
		 * 启动另外的线程对数据库进行插入操作插入测试用的数据
		 */
		HandlerThread handlerThread = new HandlerThread("db init");
		handlerThread.start();
		final AppInitHander hander = new AppInitHander(this,
				handlerThread.getLooper());
		hander.post(new Runnable() {
			@Override
			public void run() {

				String shopName = "大洋百货光谷店";
				String shopAddress = "东湖新技术开发区光谷世界城光谷街3号1区101号";
				// String shopTelephone = "(027)87418888";
				Random random = new Random();
				Shop shop = new ShopLocal();
				synchronized (application.getLocalDB()) {

					/*
					 * 创建sd卡文件和文件夹
					 */
					try {
						StorageUtils.buildLocalDataDirectory();
					} catch (IOException e) {
						e.printStackTrace();
					}

					/*
					 * 把包含城市代码和名字等信息的数据库方如程序的独立路径
					 */
					AssetManager assetManager = getAssets();
					OutputStream outputStream;
					InputStream inputStream;
					try {
						inputStream = assetManager.open("city.db");
						File dbFile = new File(
								"//data//data//com.hust360.percent//databases");
						if (!dbFile.isDirectory()) {
							dbFile.mkdir();
						}
						dbFile = new File(
								"//data//data//com.hust360.percent//databases//city.db");
						if (!dbFile.isFile())
							dbFile.createNewFile();
						Log.i("FirstRunActivity",
								"db file path is " + dbFile.getAbsolutePath());
						outputStream = new FileOutputStream(dbFile);
						byte[] buff = new byte[512];
						while (inputStream.read(buff) != -1) {
							outputStream.write(buff);
						}
						inputStream.close();
						outputStream.close();

						citydb = SQLiteDatabase.openDatabase(
								dbFile.getAbsolutePath(), null,
								SQLiteDatabase.OPEN_READONLY);
						application.setCityDB(citydb);

					} catch (IOException e1) {
						e1.printStackTrace();
					}

					/*
					 * 设置程序第一次运行的标志为false
					 */
					Editor edit = sharedPreferences.edit();
					edit.putBoolean(PercentApplication.APP_IS_FIRST_RUN, false);
					edit.commit();

					// 先获得一个省份和城市的列表
					Cursor cityc = citydb.query("city", new String[] { "id" },
							null, null, null, null, null);
					Long[] cityIds = new Long[cityc.getCount()];
					int l = 0;
					while (cityc.moveToNext()) {
						cityIds[l] = cityc.getLong(0);
						l++;
					}
					cityc.close();

					String[] filenames;
					File file = null;
					try {
						file = new File(StorageUtils.getSDPath() + "//file//");
					} catch (IOException e) {
						e.printStackTrace();
					}
					filenames = file.list();

					/*---------------------------插入1000条测试数据-----------------------------------*/
					// 插入店铺的数据
					for (int i = 0; i < 500; i++) {
						shop.address = (shopAddress + i);
						shop.areaid = (long) random.nextInt(100); // 1000 个区域
						shop.brandid = (long) random.nextInt(100); // 500个品牌
						shop.cityid = (cityIds[random.nextInt(cityIds.length)]);
						shop.id = (StorageUtils.curMaxShopId);
						shop.latitude = (90 * random.nextDouble() * (random
								.nextBoolean() ? 1 : -1));
						shop.logoimg = filenames[random
								.nextInt(filenames.length)];
						shop.logoURL = "";
						shop.longitude = (180 * random.nextDouble() * (random
								.nextBoolean() ? 1 : -1));
						// shop.moddate = null;
						shop.name = shopName + i;
						shop.subname = "--" + random.nextInt(1000);
						shop.telephone = (random.nextInt(200) + "" + Math
								.abs(random.nextLong() % 100000000));
						shop.type = random.nextInt(6);
						shopDAO.save(shop);
						StorageUtils.curMaxShopId++;
					}
					edit.putLong(StorageUtils.CUR_MAX_SHOP_ID_KEY,
							StorageUtils.curMaxShopId);
					edit.commit();

					// 插入打折信息的测试数据和对应的图片信息
					Discount info = new DiscountLocal();
					Image image = new Image();
					for (int i = 0; i < 100; i++) {
						info.describe = "打折的信息" + i;//
						info.discount = (random.nextInt(11));
						info.disctype = (random.nextBoolean() ? 1 : 0);
						info.id = (StorageUtils.curMaxDiscountId);
						info.shopid = Math.abs(random.nextLong()
								% (StorageUtils.curMaxShopId - 1));

						image.dscid = info.id;
						for (int j = 0; j < 5; j++) {
							image.filename = filenames[random
									.nextInt(filenames.length)];
							image.url = image.filename;
							PercentApplication.imageDAO.save(image);
						}

						discountInfoDAO.save(info);
						StorageUtils.curMaxDiscountId++;
					}

					/*
					 * 插入区域信息测试数据
					 */

					Area area = new AreaLocal();
					try {
						file = new File(StorageUtils.getSDPath()
								+ "//area_file");
						if (!file.isDirectory())
							file.mkdir();
						String[] IMGS = file.list();
						for (int k = 0; k < 100; k++) {
							area.id = StorageUtils.curMaxAreaId;
							area.cityId = cityIds[random
									.nextInt(cityIds.length)];
							area.name = "区域"+random.nextInt();
							area.latitude = (90 * random.nextDouble() * (random
									.nextBoolean() ? 1 : -1));
							area.longitude = (180 * random.nextDouble())
									* (random.nextBoolean() ? 1 : -1);
							area.setId(StorageUtils.curMaxAreaId);
							area.setTitle("的撒发算去额" + random.nextInt());
							area.setImg(IMGS[random.nextInt(IMGS.length)]);
							area.setType(random.nextInt(6));
							areaDAO.save(area);

							StorageUtils.curMaxAreaId++;
						}
					} catch (IOException e) {
						e.printStackTrace();
					}

					// 向用户表插入用户信息,仅仅插入一条作为测试
					{
						User user = new UserLocal();
						user.id = 1L;
						// user.img = //图片没提供
						user.mail = "354715689@qq.com";
						user.password = "123456";
						user.username = "lys3547";
						PercentApplication.userDAO.save(user);
					}

					/*
					 * 插入评论信息
					 */

					edit.putLong(StorageUtils.CUR_MAX_DISCOUNT_ID_KEY,
							StorageUtils.curMaxDiscountId);
					edit.commit();
				}
				Message message = hander.obtainMessage();
				message.arg1 = 1;
				hander.sendMessage(message);
			}
		});

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		ActivityUtils.removeActivity(this);
	}

	private static class AppInitHander extends Handler {

		Activity activity;

		private AppInitHander(Activity activity, Looper looper) {
			super(looper);
			this.activity = activity;
		}

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.arg1 == 1) {
				activity.setResult(RESULT_OK);
				Intent intent = new Intent(activity, MainActivity.class);
				activity.startActivity(intent);
				activity.finish();
				this.getLooper().quit();

			}
		}
	}

}
